import { HttpClient, HttpHeaders, HttpParams } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { Buildings } from './buildings';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/forkJoin'
import { UserSettingProvider } from '../user-setting/user-setting';
import { SqliteHelperProvider } from '../sqlite-helper/sqlite-helper';


@Injectable()
export class BuildingsDataProvider {

  private readonly baseUrl: string = 'https://api.bmob.cn/1';
  private readonly httpHeaders : HttpHeaders = new HttpHeaders(
    {
      'X-Bmob-Application-Id':'748054e798358354bf419b92c0dd9638',
      'X-Bmob-REST-API-Key':'452b75414d0a4920470d5ff482cb451d',
      'Content-Type':'application/json'
    }
  );

  constructor(
    public http: HttpClient,
    private userSettingProvider:UserSettingProvider , 
    private sqliteHelperProvider:SqliteHelperProvider){
  }

  // 返回多个数据
  /**
   * 分页获取楼栋数据
   * @param num 
   * @param page 
   */
  getBuildings(num : number, page: number):Observable<Buildings[]>{
    let _params = new HttpParams()
    .set('limit',`${num}`)
    .set('skip',`${(page-1)*num}`);
    return this.http.get<Buildings[]>(`${this.baseUrl}/classes/buildings`,
    {headers: this.httpHeaders, params: _params}).map(_=>_['results']);
  }

   /**
   * 获取纪录条数
   */
  getCount(): Observable<number>{
    return this.http.get<number>(`${this.baseUrl}/classes/buildings?limit=0&count=1`,
    {headers: this.httpHeaders}).map(data=>data['count']);
  }

  /**
   * 获取所有纪录
   * @param total 纪录总数
   */
  getAllBuildings(total:number):Observable<Buildings[][]>{
    let num = 1;
    let all: Observable<Buildings[]>[]=[];
    for (let index = 0; index < total / num; index++) {
      let _params = new HttpParams()
        .set('limit',`${num}`)
        .set('skip',`${index*num}`);
      all[index] = this.http.get<Buildings[]>
      (`${this.baseUrl}/classes/buildings`,
      {headers: this.httpHeaders,params:_params}).map(_ => _['results']);
    }
    return Observable.forkJoin(all);
  }

  /**
   * 缓存HTTP数据到本地
   */
  setBuildingsToCache():Promise<any>{
    return new Promise<any>((resolve,reject)=>{
      this.userSettingProvider.isRefreshData()
        .then(isRefresh => {
          console.log(`是否刷新：${isRefresh}`);
          if (isRefresh) {
            this.sqliteHelperProvider.createOrOpenDb() //打开或新建数据
              .then(()=>{
                return this.sqliteHelperProvider.executeSql('DELETE FROM buildings_lite',[]);//清空原有数据库中的数据，即清空缓存
              }).then(()=>{
                return this.getCount().toPromise();//获取远端数据记录数
              }).then(total=>{
                return this.getAllBuildings(total).toPromise();//获取远端数据
              }).then(data=>{
                data.forEach(buildings=>{
                  console.log(`待加入数据：${buildings.length}`);
                  let sql = 'INSERT INTO buildings_lite (objectId, name, point)';
                  sql += ` SELECT '${buildings[0].objectId}', '${buildings[0].name}', '${buildings[0].point}'`;
                  for (let i = 1; i < buildings.length; i++) {
                    sql += ` UNION ALL SELECT '${buildings[i]}.objectId', '${buildings[i]}.name', '${buildings[i]}.point'`;
                  }
                  this.sqliteHelperProvider.executeSql(sql,[]);
                });// 插入数据到数据库中，即建立缓存
              })
              ;
          }
          
        });
    });
    
  }
  /**
   * 从缓存中读取记录数
   */
  getBuildingsFromCache() : Promise<any>{
    return this.sqliteHelperProvider.createOrOpenDb()
    .then(()=>{
      return this.sqliteHelperProvider.executeSql('SELECT * FROM buildings_lite',
      []);
    });
  }
/**
 * 获取缓存记录数
 */
getCacheCount() : Promise<any>{
  return this.sqliteHelperProvider.createOrOpenDb().then(()=>{
   return this.sqliteHelperProvider.executeSql('SELECT COUNT(1) AS count FROM buildings_lite',[]);
  });
}

}
